package com.cmcc.qx.ws.controller;

import java.awt.Image;
import java.awt.geom.AffineTransform;
import java.awt.image.AffineTransformOp;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Set;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.cmcc.qx.common.entity.Article;
import com.cmcc.qx.common.entity.BackBean;
import com.cmcc.qx.util.HttpUtil;
import com.cmcc.qx.util.PageUtil;
import com.cmcc.qx.util.ToHtmlUtil;
import com.cmcc.qx.ws.service.ArticleService;
import com.cmcc.qx.ws.service.BackAtrService;

@Controller
public class BackAtrController {

	private static final Logger logger = Logger
			.getLogger(BackAtrController.class);
	
	private static final int limit = 10;

	@Resource(name = "BackArtServiceImpl")
	private BackAtrService backAtrService;

	@Resource(name = "ArticleServiceImpl")
	private ArticleService articleService;

	/**
	 * 添加文章
	 * 
	 * @param request
	 * @param response
	 * @throws IOException
	 */
	@RequestMapping(value = "/umeditor/addAtr.do", method = RequestMethod.POST)
	public void addAtr(HttpServletRequest request, HttpServletResponse response)
			throws IOException {
		request.setCharacterEncoding("UTF-8");
		DiskFileItemFactory factory = new DiskFileItemFactory();
		ServletFileUpload upload = new ServletFileUpload(factory);
		try {
			List items = upload.parseRequest(request);
			Iterator itr = items.iterator();
			Article art = new Article();
			while (itr.hasNext()) {
				FileItem item = (FileItem) itr.next();
				art.setVisits(0);
				art.setTop(0);
				art.setCreateTime(new Date());
				art.setSts("A");
				if (item.isFormField()) {
					// System.out.println("表单参数名:" + item.getFieldName()
					// + "，表单参数值:" + item.getString("UTF-8"));
					if (item.getFieldName().equals("arttitle")) {
						art.setTitle(item.getString("UTF-8"));
					} else if (item.getFieldName().equals("text")) {
						art.setText(item.getString("UTF-8"));
					} else if (item.getFieldName().equals("type")) {
						art.setType(Integer.valueOf(item.getString("UTF-8")));
					} else if (item.getFieldName().equals("tag")) {
						art.setTag(item.getString("UTF-8"));
					} else if (item.getFieldName().equals("onlytext")) {
						art.setOnlytext(item.getString("UTF-8"));
					}
				} else {
					if (item.getName() != null && !item.getName().equals("")) {
						// System.out.println("上传文件的大小:" + item.getSize());
						// System.out.println("上传文件的类型:" +
						// item.getContentType());
						// item.getName()返回上传文件在客户端的完整路径名称
						// System.out.println("上传文件的名称:" + item.getName());
						SimpleDateFormat sdf = new SimpleDateFormat(
								"yyyyMMddHHmmss");
						String today = sdf.format(new Date());
						today = today + "." + item.getName().split("\\.")[1];
						File tempFile = new File(today);

						// 上传文件的保存路径
						// ！！！！！！！！！！！！此处修改为配置文件！！！！！！！！！
						File file = new File(request.getSession()
								.getServletContext().getRealPath("")
								+ File.separator
								+ "upload"
								+ File.separator
								+ "titleImg"
								+ File.separator
								+ tempFile.getName());
						logger.info("filePath=" + file.getPath());
						item.write(file);
						Image iSmall = this.zoomPicFix(file, 110, 120);
						ImageIO.write((BufferedImage) iSmall, "jpg", file);
						request.setAttribute("upload.message", "上传文件成功！");
						art.setPicpath("upload" + File.separator + "titleImg"
								+ File.separator + tempFile.getName());
					} else {
						// response.sendError(404, "没有上传的图片");
					}
				}
			}
			backAtrService.addArt(art);
			HttpUtil.write(response.getOutputStream(), "ok");
		} catch (Exception e) {
			logger.error("文章添加失败", e);
			response.sendError(500);
		}
	}

	/**
	 * 加载详细文章html
	 * 
	 * @param request
	 * @param response
	 * @throws IOException
	 * @throws IOException
	 */
	@RequestMapping(value = "/back/addHtml.do", method = RequestMethod.GET)
	public void addHtml(HttpServletRequest request, HttpServletResponse response)
			throws IOException {
		try {
			List<Article> arts = articleService.queryArt();
			List<Article> hotArts = articleService.queryRank();
			List<String> tags = articleService.queryTag();
			for (Article art : arts) {
				// String path = request.getContextPath();
				// this.getClass().getResource("/").getPath();
				// ~！！！！！！！！！！！！！！！此处需要修改为配置文件加载！！！！！！！！！！！！！！！！！！
				// File file = new File(System.getProperty("catalina.home")
				// + "/webapps/xianqu/npage/" + art.getId() + ".html");
				File file = new File(request.getSession().getServletContext()
						.getRealPath("")
						+ File.separator
						+ "npage"
						+ File.separator
						+ art.getId() + ".html");
				logger.info("ArtfilePath=" + file.getPath());
				boolean f = ToHtmlUtil.JspToHtmlFile(file, art, hotArts, tags,
						request.getSession().getServletContext()
								.getRealPath("")
								+ File.separator
								+ "nresources"
								+ File.separator + "base.html");
				if (!f) {
					response.sendError(500);
					return;
				}
			}
			HttpUtil.write(response.getOutputStream(), "ok");
		} catch (Exception e) {
			response.sendError(500);
		}
	}
	
	/**
	 * 查询修改文章
	 * @param bean
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value = "/back/querylist.do", method = RequestMethod.POST)
	public String queryArt(@ModelAttribute BackBean bean, HttpServletRequest request, HttpServletResponse response) {
		if(bean.getPage()==""){
			bean.setPage("1");
		}
		int currentPage = Integer.valueOf(bean.getPage());
		int start = (currentPage - 1)*limit;
		List<Article> arts = backAtrService.queryArt(start, limit, bean);
		request.setAttribute("arts", arts);
		
		int cnt = backAtrService.queryCnt(bean);
		Set<Integer> index = PageUtil.paginate(cnt, limit, currentPage);
		int endnum = cnt/limit;
		if(cnt%limit>0){
			endnum++;
		}
		//分页
		request.setAttribute("index", index);
		request.setAttribute("endnum", endnum);
		request.setAttribute("page", currentPage);
		request.setAttribute("bean", bean);
		
		return "/back/queryArt.jsp";
	}
	/**
	 * 删除文章
	 * @param request
	 * @param response
	 */
	@RequestMapping(value="/back/delAtr.do", method = RequestMethod.GET)
	public void delAtr(HttpServletRequest request, HttpServletResponse response){
		String idsStr = (String) request.getParameter("ids");
		List<String> ids = new ArrayList<String>();
		ids = Arrays.asList(idsStr.split(","));
		backAtrService.deleteArt(ids);
	}
	
	/**
	 * 隐藏文章
	 * @param request
	 * @param response
	 */
	@RequestMapping(value="/back/hiddenAtr.do", method = RequestMethod.GET)
	public void hiddenArt(HttpServletRequest request, HttpServletResponse response){
		String idsStr = (String) request.getParameter("ids");
		List<String> ids = new ArrayList<String>();
		ids = Arrays.asList(idsStr.split(","));
		backAtrService.hiddenArt(ids);
	}
	
	@RequestMapping(value="/back/showAtrDetail.do", method = RequestMethod.GET)
	public String queryArtDetail(HttpServletRequest request, HttpServletResponse response){
		String id = (String)request.getParameter("id");
		Article art = articleService.queryById(Integer.valueOf(id));
		request.setAttribute("art", art);
		return "/back/npage/atrDetail.jsp";
	}


	/**
	 * 缩放图片源文件，按固定长宽
	 * 
	 * @param Pic
	 * @param width
	 * @param height
	 * @return
	 * @throws IOException
	 */
	private Image zoomPicFix(File Pic, int width, int height)
			throws IOException {
		BufferedImage Bi = ImageIO.read(Pic);

		double ratioX = (double) width / Bi.getWidth();
		double ratioY = (double) height / Bi.getHeight();
		AffineTransformOp op = new AffineTransformOp(AffineTransform
				.getScaleInstance(ratioX, ratioY), null);
		Image iTemp = op.filter(Bi, null);
		return iTemp;
	}
}
